#!/bin/bash +x

function start_services() {
    # Run apache
    /opt/portage/usr/sbin/apache2 -f /opt/portage/etc/apache2/httpd.conf &
    export apache_pid=$((${!} + 1))

    # Run rsync
    rsync --daemon --config ~/etc/rsyncd.conf
    export rsync_pid=$!
    rsync_pid=$((${rsync_pid} + 1))

    if [[ ! -d ~/services ]]; then
	mkdir -p ~/services
    fi

    # Store pids
    echo "${apache_pid}" >> ~/services/apache.pid
    echo "${rsync_pid}" >> ~/services/rsync.pid
}

function stop_services() {
    apache_pid=`cat ~/services/apache.pid`
    rsync_pid=`cat ~/services/rsync.pid`
    
    stop_apache ${apache_pid}
    stop_rsync ${rsync_pid}
    if [[ "$?" != 0 ]]; then
	echo "Rsync not stopped succesfully! Pid ${rsync_pid}"
    fi
}


function stop_rsync() {
    rsync_pid=$1

    kill "${rsync_pid}"
    if [[ "$?" == 0 ]]; then
	rm -f ~/services/rsync.pid
    fi
    return $?
}

function stop_apache() {
    apache_pid=$1

    if [[ ! -f "~/services/apache.pid" ]]; then
	echo "Apache pid file not found, apache not started or pid not created"
    else
	echo "Killing apache pid ${apache_pid}..."
	kill "${apache_pid}"
	timer=0
	`ps -ef | grep apache2`
	grep=$?
	while [ grep != 1 ]; do
	    procs=`ps -ef | grep apache2`
	    grep=$?
	    echo "Sleeping for 5sec, if apache still up in 60sec we will force kill it"
	    sleep 5
	    timer=$((${timer} + 1))
	    if [[ "${timer}" == 13 ]]; then
		echo "Force killing apache..."
		for line in "${procs}"; do
		    echo "${line}" | awk '{ if (\$2 == ${apache_pid}) { exit 0 } }'
		    if [[ "$?" == 0 ]]; then
			kill -9 "${apache_pid}"
			grep=1
		    fi
		done
	    fi
	done
	rm -f ~/services/apache.pid
    fi
    return 0
}

function restart_services() {
    stop_services
    sleep 1s
    start_services
}


function usage() {
    echo -e "\nUsage:\n\t${0} start\n\t${0} stop\n\t${0} restart\n"
}


if [[ "$#" != 1 ]]; then
    usage
else
    case "${1}" in
	"start")
	    start_services;
	    ;;
	"stop")
	    stop_services;
	    ;;
	"restart")
	    restart_services;
	    ;;
	*)
	    usage;
	    ;;
    esac
fi